package es.castorm.business.customer.internal;

import java.util.ArrayList;
import java.util.List;

import ma.glasnost.orika.MapperFacade;

import org.springframework.beans.factory.annotation.Autowired;

import es.castorm.arch.service.Service;
import es.castorm.business.customer.CustomerCriteriaDTO;
import es.castorm.business.customer.CustomerDTO;
import es.castorm.business.customer.CustomerService;

@Service
public class CustomerServiceImpl implements CustomerService {

	@Autowired
	MapperFacade mapper;

	@Autowired
	CustomerDao customerDao;

	public CustomerDTO findCustomer(Long id) {
		Customer customer = customerDao.find(id);
		return mapper.map(customer, CustomerDTO.class);
	}

	public CustomerDTO createCustomer(CustomerDTO customer) {
		Customer entity = mapper.map(customer, Customer.class);
		entity = customerDao.save(entity);
		mapper.map(entity, customer);
		return customer;
	}

	public List<CustomerDTO> findCustomers(CustomerCriteriaDTO criteria) {
		Iterable<Customer> entities = customerDao.find(criteria);
		List<CustomerDTO> customers = new ArrayList<CustomerDTO>();
		mapper.mapAsCollection(entities, customers, CustomerDTO.class);
		return customers;
	}

	public CustomerDTO updateCustomer(CustomerDTO customer) {
		Customer entity = mapper.map(customer, Customer.class);
		entity = customerDao.save(entity);
		mapper.map(entity, customer);
		customer.setVersion(customer.getVersion() + 1);
		return customer;
	}

	public void deleteCustomer(CustomerDTO customer) {
		Customer entity = mapper.map(customer, Customer.class);
		customerDao.delete(entity);
	}
}
